package com.yhp.web;

import com.yhp.bean.Grade;
import com.yhp.bean.Student;
import com.yhp.service.GradeService;
import com.yhp.service.StudentService;
import com.yhp.service.impl.GradeServiceImpl;
import com.yhp.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = {"/Educational/student/"})
public class StudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String method = req.getParameter("method");
        if (method.equals("delstu")) {
            delstudent(req, resp);
        } else if ("findbyid".equals(method)) {
            findbyid(req, resp);
        }
    }
    //主键查询
    protected void findbyid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("sid");

        StudentService studentService=new StudentServiceImpl();
        Student stu=studentService.findbyid(sid);
        req.setAttribute("stu",stu);
        //查询年级列表
        GradeService gradeService=new GradeServiceImpl();
        List<Grade> grades=gradeService.getGrades();
        req.setAttribute("glist",grades);
        req.getRequestDispatcher("edit.jsp").forward(req,resp);

    }
    //删除学生
    protected void delstudent(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
        //1.接收参数
        String sid = req.getParameter("sid");
        //2.调取方法
        StudentService studentService=new StudentServiceImpl();
        int del=studentService.del(sid);
        //3.跳转页面
        //后台给前台一个弹窗
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer=resp.getWriter();
        if(del>0){
            writer.println("<script>alert('删除成功');location.href='/Educational/student/getstudents'</script>");
        }else{
            writer.println("<script>alert('删除失败');location.href='/Educational/student/getstudents'</script>");
        }
    }
}
